import xlwt
import json
import time
from lxml import etree
import requests
from Utils.sendEmail import SendEMail

from Utils.public_func import Profile, TeambitionConnect, convert_time
from Utils.readconfig import ReadConfig


class TeambitionSpider(object):
    def __init__(self):
        self.config = ReadConfig()
        self.p = Profile()
        self.todayDate = self.p.todayDate

        self.cache_dict = {}
        self.cookies = {}
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.16; rv:83.0) Gecko/20100101 Firefox/83.0',
            'x-organization-id': '5dc1190812a69c000166b661',
            'x-user-id': '5f811fcdb566d2900fa58fe7',

            # 需要获取：Authorization 值
            'Authorization': 'Bearer eyJhbGciOiJFZDI1NTE5IiwidHlwIjoiSldUIn0.eyJhcHAiOiI1Y2RjZmU5YTUxNWY1MDAwMDFmMDZkNzEiLCJhdWQiOiI1ZGMxMTkwODEyYTY5YzAwMDE2NmI2NjEiLCJleHAiOjE2Mzg1MTY4NzQsImlhdCI6MTYwNjk4MDg3NCwiaXNzIjoidHdzIiwianRpIjoiSEF6N3NFMVFvd0c1bUJ6MzB0dUtXRExDbGtJZjRCQW1zNU0yTUd1UUdFaz0iLCJyZW5ld2VkIjoxNjAzODU3ODYxOTg1LCJzY3AiOlsiYXBwX3VzZXIiXSwic3ViIjoiNWY4MTFmY2RiNTY2ZDI5MDBmYTU4ZmU3IiwidHlwIjoiYWNjZXNzX3Rva2VuIn0.X25IuVlhKFYaZd1h79gO---vcoooIb5dGadvG0Xc6U140mb6bfZwCarCin_PTixYCqXVOelrOLql3d8faDX0BQ',
        }
        self.top_str_list = []
        self.taskId_dict = {}

        self.host = self.config.email('email_host')
        self.port = self.config.email('email_port')
        self.msg_from = self.config.email('email_msg_from')
        self.to_users = self.config.email('email_to_users')

        self.filename = self.p.filename

        self.password = self.config.user_pwd('password')
        self.email = self.config.user_pwd('email')

    def s(self):
        return requests.Session()

    def get_token(self):

        response = requests.get('https://account.teambition.com/login', headers=self.headers)
        html = response.text
        p = etree.HTML(html)
        result = p.xpath('//script[@id="accounts-config"]/text()')[0].strip()
        data_dict = json.loads(result)
        return data_dict['TOKEN']

    def login(self):
        token = self.get_token()
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.16; rv:83.0) Gecko/20100101 Firefox/83.0',
                   'Content-Type': 'application/json', }
        data = {"password": self.password,
                "token": token,
                "client_id": "90727510-5e9f-11e6-bf41-15ed35b6cc41", "response_type": "session",
                "email": self.email}

        response = self.s().post('https://account.teambition.com/api/login/email', headers=headers,
                                 data=json.dumps(data))
        self.cookies = response.cookies
        print('登陆状态', response)

    def send(self):
        return SendEMail(self.host, self.port, self.msg_from, self.pwd)

    def send_email_file(self):
        content = self.todayDate + 'teambition更新详情'
        subject = 'Streffy 工时更新 ' + self.todayDate
        reports_path = self.filename
        filename = self.filename
        send_E = SendEMail(self.host, self.port, self.msg_from, self.pwd)
        for to_user in self.to_users:
            send_E.send_file(to_user, content, subject, reports_path, filename)
            print('发送邮件至：', to_user)

    def send_email_text(self):
        content = self.todayDate + '无新更新信息'
        subject = 'Streffy 工时更新 ' + self.todayDate
        self.send()
        for to_user in self.to_users:
            self.send().send_text(to_user, content, subject)
            print('发送邮件至：', to_user)

    def get_taskIds(self):
        """
        由于 Authorization 未知 暂时在 init 中 写死
        :return: 保存到全局 taskId_dict
        """

        params = (
            ('_userId', '5f811fcdb566d2900fa58fe7'),
            ('userId', '5f811fcdb566d2900fa58fe7'),
            ('startDate', '2020-12-16'),
            ('endDate', '2020-12-16'),
            ('pageSize', '50'),
            ('pageToken', ''),
        )

        response = self.s().get('https://apps.teambition.com/work-time-server/api/tasks/track', headers=self.headers,
                                params=params)

        for item in response.json()['payload']['result']:
            self.taskId_dict[item['content'] + '_' + item['project']['name']] = item['_id']

    def task_content(self, _id):
        """
        获得任务中的所有数据
        :param _id:
        :return: 任务中所有时间段dict数据
        """
        params = (
            ('_id', _id),
            ('isMobile', '$isMobile$'),
            ('version', '1.0.0'),
            ('lang', 'zh'),
            ('page', '1'),
            ('count', '99'),
            ('_', int(time.time() * 1000)),
        )

        response = requests.get(
            'https://appshell.teambition.com/api/v1/organization/5dc1190812a69c000166b661/extension/5dba4d9639c843002d6b3d15/slotRequest',
            headers=self.headers, params=params, cookies=self.cookies)
        return response.json()['data']

    def process_data(self, result_list):
        # """
        #
        # :param dict_: dict_ = {'2-上新，更新1号菜单-批萨玛尚诺项目支持': '樊正阳-11月30日', '2-测试用例撰写-批萨玛尚诺项目支持': '樊正阳-11月30日',
        #          '4-汉堡王4家加盟商建店&审核-汉堡王项目支持': '樊正阳-11月30日', '8-修改底栏界面，标注切图-哈根达斯售前支持': '马珺怡-11月30日',
        #          '8-1.小杨生煎测试2.促销功能测试3.后台banner部分画图-公司事务': '罗真真-11月30日'}
        # """
        # print('ss',dict_)
        # for v, k in dict_.items():
        #     self.top_str_list.append(k)
        #
        # result_dict = {}
        # for item in list(set(self.top_str_list)):
        #     if item in dict_.values():
        #         cache_ = []
        #         for index in range(0, len(dict_)):
        #             if item in list(dict_.values())[index] == item:
        #                 __dict__ = {}
        #                 __list__ = list(dict_.keys())[index].split('#')
        #                 # print(__list__)
        #                 __dict__['hours'] = __list__[0]
        #                 __dict__['content'] = __list__[1]
        #                 __dict__['title'] = __list__[2]
        #                 cache_.append(__dict__)
        #         result_dict[item] = cache_
        # print('数据获取成功')
        # result_list = []
        # for k, v in result_dict.items():
        #     hours = sum([int(i['hours']) for i in v])
        #     result_list.append(
        #         [
        #             str([i for i in k.split('-')]).replace('[', '').replace(']', '').replace("'", '').split(',')[1],
        #             str([i for i in k.split('-')]).replace('[', '').replace(']', '').replace("'", '').split(',')[0],
        #             str(list(set([(i['title']) for i in v]))).replace('[', '').replace(']', '').replace("'", ''),
        #             str([(i['content']) for i in v]).replace('[', '').replace(']', '').replace("'", ''),
        #             str(hours),
        #         ]
        #
        #     )
        # print(result_list)
        if result_list:
            self.save_to_xls(result_list)

            print('将附件以邮件形式发送')

            # self.send_email_file()
        else:
            print(self.todayDate, '发送无记录邮件')
            # self.send_email_text()

    def save_to_xls(self, list_):
        # 创建一个workbook 设置编码
        workbook = xlwt.Workbook(encoding='utf-8')
        # 创建一个worksheet
        worksheet = workbook.add_sheet('My Worksheet')

        # 写入excel
        worksheet.write(0, 0, label='日期')
        worksheet.write(0, 1, label='员工')
        worksheet.write(0, 2, label='任务')
        worksheet.write(0, 3, label='工作描述')
        worksheet.write(0, 4, label='工作时长')

        for column in range(0, len(list(list_))):

            # print(column,str_list[column])
            for row in range(0, len(list(list_[column]))):
                worksheet.write(column + 1, row, label=list_[column][row])

        # 保存
        workbook.save(self.filename)

    def run(self):
        count = 1
        result_list = []
        print('Start')
        self.login()

        # init 中暂时写死 taskIds
        self.get_taskIds()
        # print(self.taskId_dict)
        print('正在获取数据')
        for task, _id in self.taskId_dict.items():
            data = self.task_content(_id)
            for item in data:
                title_data = item['title'].split(' ')
                name = title_data[0]
                date = title_data[1].replace('实际工时为', '')
                times = title_data[2]
                description = item['description'].replace('\n', '')
                try:
                    print('最终数据：',convert_time(date), name, ''.join(task.split()), description, times)
                    with TeambitionConnect()as t:
                        t.inset_data(convert_time(date), name, ''.join(task.split()), description, times)
                    result_list.append([self.p.year + self.todayDate, name, ''.join(task.split()), description, times])
                    task_name = times + '#' + description + '#' + task
                    if task_name in self.cache_dict.keys():
                        count += 1
                        task_name = task_name + str(count)
                    self.cache_dict[task_name] = name + '-' + date
                except ValueError:
                    # 错误数据丢弃
                    pass

        if self.config.save_xls('save_to_xls') == 'True':
            self.process_data(result_list)
        print('END')


def start():
    work = TeambitionSpider()
    work.run()
